//API 操作
const API = require('../../datas/common.js');
let app = getApp();

//创建精选页面对象
Page({
    data: {
        messages: [],
        openId: '',
        touchStart: 0,
        touchEnd: 0
    },
    onLoad: function () {
        let that = this;
        API.getUserInfo().then(res => {
            let userInfo = res;
            API.showLoading('加载中...');
            API.get('/message/attention').then(res => {
                that.setData({
                    openId: userInfo.openId,
                    messages: res.data,
                })
                that.onLoadMerge(res.data);
                API.hideLoading();
            }).catch((res) => {
                API.showToast(res.message);
            });
            that.initWebSocket(userInfo.openId);
            app.addMessageListener(function (changedData) {
                let data = changedData[0];
                let message = {
                    contentId: data.id,
                    openId: data.openId,
                    authorOpenId: data.openId,
                    description: data.description,
                    unreadCount: 0
                }
                let newIndex = that.data.messages.length;
                that.setData({
                    ['messages[' + newIndex + ']']: message
                })
            });
            app.addCommentListener(function (changedData) {
                let index = that.data.messages.findIndex(function (element) {
                    return element.contentId == changedData.contentId;
                });
                let messageResult = that.data.messages[index];
                messageResult.date = changedData.date;
                messageResult.commentUserName = changedData.commentUserName;
                messageResult.message = changedData.message;
                that.setData({
                    ['messages[' + index + ']']: messageResult
                })
            });
        }).catch((res) => {
            API.showToast(res.message);
        })
    },
    initWebSocket: function (openId) {
        let that = this;
        //建立连接
        wx.connectSocket({
            url: API.getSocketUrl(openId)
        })

        //连接成功
        wx.onSocketOpen(function () {
            console.info('websocket连接成功');
        })

        //接收数据
        wx.onSocketMessage(function (data) {
            let jsonData = JSON.parse(data.data);
            if (jsonData.type == 'NEARBY_COMMENT') {
                let message = {
                    contentId: jsonData.contentId,
                    unreadCount: 1,
                    date: jsonData.created.substring(11, 16),
                    commentUserName: jsonData.authorName,
                    message: jsonData.message
                }
                that.socketMerge(message);
            }
        })

        //连接失败
        wx.onSocketError(function () {
            console.info('websocket连接失败！');
        })

        wx.onSocketClose(function (res) {
            console.log('websocket已关闭！')
        })
    },
    editMessage: function (event) {
        let that = this;
        let contentId = event.currentTarget.dataset.id;
        let index = event.currentTarget.dataset.index;
        let touchTime = that.data.touchEnd - that.data.touchStart;
        if (touchTime > 350) {
            let isSelf = app.globalData.userInfo.openId == event.currentTarget.dataset.openid;
            let itemName = isSelf ? '删除' : '取消关注';
            wx.showActionSheet({
                itemList: [itemName],
                success: function (res) {
                    if (res.tapIndex == 0) {
                        if (isSelf) {
                            that.deleteNearbyContent(contentId, index);
                        } else {
                            that.cancelAttention(contentId, index);
                        }
                    }
                    API.removeStorage('wuxuegai_unread_' + contentId);
                    API.removeStorage('wuxuegai_comment_' + contentId);
                }
            })
        } else {
            that.showDetail(contentId, index);
        }
    },
    deleteNearbyContent: function (contentId, index) {
        let that = this;
        API.delete('/content/nearby/' + contentId).then(res => {
            let messages = that.data.messages;
            messages.splice(index, 1);
            that.setData({
                messages: messages
            });
        });
    },
    cancelAttention: function (contentId, index) {
        let that = this;
        API.delete('/message/attention/' + contentId).then(res => {
            let messages = that.data.messages;
            messages.splice(index, 1);
            that.setData({
                messages: messages
            });
        });
    },
    showDetail: function (contentId, index) {
        this.setData({
            ['messages[' + index + '].unreadCount']: 0
        });
        API.setStorage('wuxuegai_unread_' + contentId, 0)
        wx.navigateTo({
            url: '/pages/nearby/detail/detail?type=NEARBY&id=' + contentId
        })
    },
    touchStart: function (e) {
        this.data.touchStart = e.timeStamp;
    },
    touchEnd: function (e) {
        this.data.touchEnd = e.timeStamp;
    },
    onLoadMerge: function (messages) {
        for (let i = 0; i < messages.length; i++) {
            this.merge(messages[i]);
        }
    },
    socketMerge: function (message) {
        this.merge(message);
    },
    merge: function (message) {
        let comment = this.mergeComment(message);
        let unreadCount = this.mergeUnread(message);
        let index = this.data.messages.findIndex(function (element) {
            return element.contentId == message.contentId;
        });
        if (index == -1) {
            API.get('/message/attention/' + message.contentId).then(res => {
                let newIndex = this.data.messages.length;
                this.setData({
                    ['messages[' + newIndex + ']']: res.data
                })
            });
        } else {
            let messageResult = this.data.messages[index];
            messageResult.date = comment.date;
            messageResult.commentUserName = comment.commentUserName;
            messageResult.message = comment.message;
            messageResult.unreadCount = unreadCount;
            this.setData({
                ['messages[' + index + ']']: messageResult
            })
        }
    },
    mergeComment: function (message) {
        let key = 'wuxuegai_comment_' + message.contentId;
        if (null != message.commentUserName) {
            let comment = {
                date: message.date,
                commentUserName: message.commentUserName,
                message: message.message
            };
            API.setStorage(key, comment);
            return comment;
        }
        return API.getStorage(key, true);
    },
    mergeUnread: function (message) {
        let unreadCount = message.unreadCount;
        let key = 'wuxuegai_unread_' + message.contentId
        let unreadCountStorage = API.getStorage(key, true);
        unreadCount += unreadCountStorage ? unreadCountStorage : 0;
        API.setStorage(key, unreadCount);
        return unreadCount;
    }
});